from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import CZ
import re
# Create your views here.
class CheckName(APIView):
    def get(self,request,name):
        if not re.findall(r'^[a-zA-Z]\w{4,15}$',name):
            return Response({'code':404,'msg':'验证码格式不匹配'})

        if CZ.objects.filter(name=name):
            return Response({'code':204,'msg':'用户名重复'})
        else:
            return Response({'code':200,'msg':'ok'})

class CheckMobile(APIView):
    def get(self,request,mobile):
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return Response({'code':404,'msg':'电话格式不匹配'})

        if CZ.objects.filter(mobile=mobile):
            return Response({'code':204,'msg':'电话号码重复'})
        else:
            return Response({'code':200,'msg':'ok'})

import random,string,redis
from captcha.image import ImageCaptcha
from django.http import HttpResponse
class ImgCode(APIView):
    def get(self,request,uuid):
        code = ''.join(random.sample(string.ascii_letters+string.digits,4))
        print(code)
        cap = ImageCaptcha()
        img_code = cap.generate(code)
        r = redis.Redis(host='localhost',port=6379,password=123456,db=0)
        r.set(uuid,code,ex=120)
        r.close()
        return HttpResponse(img_code,content_type='image/png')

class CheckCode(APIView):
    def get(self,request):
        uuid = request.query_params.get('imageCodeID')
        img_code = request.query_params.get('imageCode')
        r = redis.Redis(host='localhost',password=123456,port=6379,db=0)
        r_code = r.get(uuid)
        if not r_code:
            return Response({'code':204,'msg':'验证码过期'})
        if img_code.lower()==r_code.decode().lower():
            return Response({'code':200,'msg':'ok'})
        else:
            return Response({'code':404,'msg':'验证码错误'})

from .models import CZ
class Register(APIView):
    def post(self,request):
        name = request.data.get('Name')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        aggree = request.data.get('aggree')

        if not all([name,pwd,mobile]):
            return Response({'code':204,'msg':'注册信息不完整'})
        if not aggree:
            return Response({'code':204,'msg':'未同意用户协议'})
        CZ.objects.create_user(name=name,password=pwd,mobile=mobile)
        return Response({'code':'200','msg':'注册成功'})

import jwt
from Chui import settings
def generate_jwt_token(CZ):
    payload = {
        'id':CZ.id,
        'name':CZ.name,
        'mobile':CZ.mobile,
    }
    token = jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
    return token

class Login(APIView):
    def post(self,request):
        name = request.data.get('cz')
        pwd=request.data.get('pwd')
        try:
            from django.db.models import Q
            cz = CZ.objects.get(Q(name=name))
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'用户不存在'})
        if not cz.check_pwd(pwd):
            return Response({'code':204,'msg':'用户名或密码不正确'})

        token=generate_jwt_token(cz)
        return Response({
            'code':200,
            'msg':'用户%s登录成功' %cz.name,
            'token':token,
            'user':{
                'userName':cz.name,
                'uid':cz.id
            }
        })